package controlebens.controller;

import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.validator.ValidationMessage;
import controlebens.been.UsuarioInfo;
import controlebens.dao.LoginDAO;
import controlebens.interceptor.AcessoLiberado;
import controlebens.model.Login;
import javax.persistence.EntityManager;

/**
 * @author Jefferson Stachelski
 */
@Resource
public class IndexController {
    private final Result result;
    private final Validator validator;
    private final UsuarioInfo usuarioInfo;
    private final LoginDAO loginDAO;
	private final EntityManager entityManager;

	public IndexController(Result result, Validator validator, UsuarioInfo usuarioInfo, LoginDAO loginDAO, EntityManager entityManager) {
		this.result = result;
		this.validator = validator;
		this.usuarioInfo = usuarioInfo;
		this.loginDAO = loginDAO;
		this.entityManager = entityManager;
	}
    
	@AcessoLiberado
    @Path("/") @Get
    public void index(){
		//System.out.println("TESTE");
        //this.result.redirectTo(HomeController.class).home();
    }
	
	@AcessoLiberado
	@Path("/") @Post
	public void login(Login login){
		//System.out.println("Usuario: "+login.getUsuario()+"\nSenha: "+login.getSenha());
        try{
            if(this.loginDAO.validarLogin(login)){
                usuarioInfo.login(this.loginDAO.getFuncionario(login));
                this.result.redirectTo(HomeController.class).home();
            }
            else{
                validator.add(new ValidationMessage("Login e/ou senha inválidos", "usuario.login"));
                validator.onErrorUsePageOf(LoginController.class).login();
                //this.result.include("validacao", false);
                this.result.redirectTo(LoginController.class).login();
            }
        }
        catch(Exception e){
            this.result.include("erro", e.getMessage());
            this.result.redirectTo(LoginController.class).login();
        }
	}
}